<template>
  <ContentWrap>
    <div class="container-card" v-loading="loading" element-loading-text="努力加载中...">
      <el-card  class="card-list" style="background-color:#3699FF">
        <el-row :gutter="20" >
          <el-col :span="24" class="list-item-weather">
            <div class="list-item-top">
              <div class="top-weather">
                <div class="top-temp"> {{weatherList.degree}} ℃</div>
                <div class="top-condition">{{weatherList.weather}}</div>
              </div>
                <!-- <div>
                    <img src ="@/assets/imgs/iot/weather.png" />
                </div> -->
            </div>

            <div class="list-item-middle">
              <div class="middle-weather">
                <div class="middle-humi">
                  <div>
                     <img src ="@/assets/imgs/iot/humi.png" />
                  </div>
                  <text>{{weatherList.humidity}} %</text>
                </div>
                <div class="middle-humi">
                  <div>
                     <img src ="@/assets/imgs/iot/wind.png" />
                  </div>
                  <text>{{weatherList.wind_power}} 级</text>
                </div>
                <div class="middle-humi">
                  <div>
                     <img src ="@/assets/imgs/iot/Pa.png" />
                  </div>
                  <text>{{weatherList.pressure}} Pa</text>
                </div>
                <div class="middle-humi">
                  <div>
                     <img src ="@/assets/imgs/iot/PM2.5.png" />
                  </div>
                  <text>{{weatherList.wind_direction_name}}</text>
                </div>
              </div>
            </div>
            <div class="list-item-bottom">
              <el-select
                v-model="farmTourValue"
                placeholder="请先选择一个农场"
                style="width: 80%"
              >
                <el-option
                  v-for="item in farmTourList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </div>
          </el-col>
        </el-row>
      </el-card> 

      <el-card  class="card-list" style="background-color:#FFB822">
        <el-row :gutter="20">
          <el-col :span="24" class="list-item">
            <div class="item-device-left" >
              <div class="device-box-status">
                <div class="status">实时告警</div>
                <div class="status-persent1">设备异常告警 {{alarm}} 个</div>
              </div>
            </div>
            <div class="item-device-right">
               <Icon icon="ep:warning" :size="33" class="mr-5px" />
            </div>
          </el-col>
        </el-row>
      </el-card>

      <el-card  class="card-list" style="background-color:#1BC5BD">
        <el-row :gutter="20">
          <el-col :span="24" class="list-item">
            <div class="item-device-left" >
              <div class="device-box-status">
                <div class="status">今日产蛋</div>
                <div class="status-persent">{{eggNUmber !== null ? eggNUmber : '-'}}  枚</div>
              </div>
              <!-- <div class="device-num">环比增长:{{number}} %</div> -->
            </div>
            <div class="item-device-right">
               <Icon icon="ep:flag" :size="33" class="mr-5px" />
            </div>
          </el-col>
        </el-row>
      </el-card>

      <el-card  class="card-list" style="background-color:#8950FC">
        <el-row :gutter="20">
          <el-col :span="24" class="list-item">
            <div class="item-device-left" >
              <div class="device-box-status">
                <div class="status">设备运行状态</div>
                <div class="status-persent">{{deviceStatus}}%</div>
              </div>
              <div class="device-num">正常运行设备:{{number}} 台</div>
            </div>
            <div class="item-device-right">
               <Icon icon="ep:monitor" :size="33" class="mr-5px" />
            </div>

          </el-col>
        </el-row>
      </el-card>
    </div>
  </ContentWrap>

  <!-- 农舍概览 -->
  <ContentWrap>
    <div class="house-monitor" v-loading="monitorListLoading" element-loading-text="努力加载中...">
      <h3>农舍概览</h3>
      <el-table :data="houseList" max-height="350" :stripe="true" :show-overflow-tooltip="true">
        <el-table-column label="序号" type="index" fixed="left" align="center" key="id" prop="id" width="60"/>
        <el-table-column label="农场名称" fixed="left" align="center" prop="houseName" />
        <el-table-column label="日龄" align="center" prop="grows" />
        <el-table-column label="存栏" align="center" prop="remain" />
        <el-table-column label="室外温度(℃)" align="center" prop="outdoorTemperature" />
        <el-table-column label="室内温度(℃)" align="center" prop="stemperature" />
        <el-table-column label="湿度(%)" align="center" prop="airHumidity" />
        <el-table-column label="负压(Pa)" align="center" prop="interPressure" />
        <el-table-column label="通风级别" align="center" prop="areationMode" />
        <el-table-column label="死淘" align="center" prop="dead" />
        <el-table-column label="耗水(m³)" align="center" prop="waterConsumption" />
        <el-table-column label="耗料(kg)" align="center" prop="materialConsumption" />
        <el-table-column label="耗电(kw/h)" align="center" prop="electricityConsumption"/>
        <el-table-column label="状态" fixed="right" align="center" prop="status">
          <template #default="{ row }">
            <span :style="{ color: getStatusColor(row.status) }">
              {{ getStatusText(row.status) }}
            </span>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </ContentWrap>
  <ContentWrap>
    <el-row :gutter="10">
      <el-col :xs="24" :sm="24" :md="14" :lg="16" :xl="16">
        <el-row :gutter="10">
          <el-col :span="24" style="margin-bottom: 10px;">
            <ContentWrap>
              <h4>蛋库概览</h4>
              <el-tabs v-loading="loading" v-model="activeName"  class="demo-tabs">
                <el-tab-pane label="分选机" name="first">
                  <el-table v-loading="loading" :data="getSortDeviceList" height="250"  :stripe="true" :show-overflow-tooltip="true">
                    <el-table-column label="序号" type="index" fixed="left" align="center" key="id" prop="id" width="60"/>
                    <el-table-column label="设备名称" fixed="left" align="center" prop="deviceName" />
                    <el-table-column label="累计在线(h)" align="center" prop="workTime">
                      <template #default="{ row }">
                        {{ (row.workTime ? (row.workTime / 3600000).toFixed(2) : '-') }}
                      </template>
                    </el-table-column>
                    <el-table-column label="收蛋舍(个)" align="center" prop="storeCount" />
                    <el-table-column label="蛋总量(枚)" align="center" prop="num" />
                    <el-table-column label="蛋总重量(kg)" align="center" prop="weight">
                      <template #default="{ row }">
                        {{ (row.weight != null ? row.weight.toFixed(2) : '-') }}
                      </template>
                    </el-table-column>
                    <el-table-column label="正常蛋(%)" align="center" prop="yield">
                      <template #default="{ row }">
                        {{ (row.yield != null ? (row.yield * 100).toFixed(2) : '-') }}
                      </template>
                    </el-table-column>
                    <el-table-column label="异常蛋(%)" align="center" prop="yield">
                      <template #default="{ row }">
                        {{ (row.yield != null ? (100 - (row.yield * 100)).toFixed(2) : '-') }}
                      </template>
                    </el-table-column>
                    <el-table-column label="状态" fixed="right" align="center" prop="status">
                      <template #default="{ row }">
                        <span :style="{ color: getStatusColor(row.status) }">
                          {{ getStatusText(row.status) }}
                        </span>
                      </template>
                    </el-table-column>
                  </el-table>
                </el-tab-pane>

                <el-tab-pane label="装托机" name="second">
                  <el-table v-loading="loading" :data="ZTJList"  height="250" :stripe="true" :show-overflow-tooltip="true">
                    <el-table-column label="序号" type="index" fixed="left" align="center" key="id" prop="id" width="60"/>
                    <el-table-column label="设备名称" fixed="left" align="center" prop="deviceName" />
                    <el-table-column label="蛋总数量" align="center" prop="number" />
                    <el-table-column label="收蛋舍(个)" align="center" prop="store" />
                    <el-table-column label="收集时间" align="center" prop="devecetime" :formatter="dateFormatter"/>
                  </el-table>
                </el-tab-pane>
              </el-tabs>
            </ContentWrap>
          </el-col>

          <el-col :span="24" style="margin-top: 10px;">
            <ContentWrap>
              <h4>发酵概览</h4>
              <el-table v-loading="loading" :data="getFJGDeviceList" height="250" :stripe="true" :show-overflow-tooltip="true">
                <el-table-column label="序号" type="index" fixed="left" align="center" key="id" prop="id" width="60"/>
                <el-table-column label="设备名称" fixed="left" align="center" prop="deviceName" />
                <el-table-column label="运行时间(min)" align="center" prop="runtime" />
                <el-table-column label="停止时间(min)" align="center" prop="stoptime" />
                <el-table-column label="出料时间(min)" align="center" prop="outtime" />
                <el-table-column label="抖料次数(次)" align="center" prop="addcount" />
                <el-table-column label="上部送风(℃)" align="center" prop="upairtemp" />
                <el-table-column label="下部送风(℃)" align="center" prop="lowairtemp" />
                <el-table-column label="罐体上部(℃)" align="center" prop="upfermenttemp" />
                <el-table-column label="罐体中部(℃)" align="center" prop="middlefermenttemp" />
                <el-table-column label="罐体下部(℃)" align="center" prop="lowfermenttemp" />
                <el-table-column label="液压搅拌压力(MPa)" align="center" prop="stirpressure" />
                <el-table-column label="下部送风压力(MPa)" align="center" prop="airpressure" />
                <el-table-column label="上风机频率(Hz)" align="center" prop="airpressure" />
                <el-table-column label="下风机频率(Hz)" align="center" prop="lowfreq" />
                <el-table-column label="状态" fixed="right" align="center" prop="warncode">
                  <template #default="{ row }">
                    <span :style="{ color: row.warncode === 0 ? 'green' : 'red' }">
                      {{ row.warncode === 0 ? '正常' : '异常' }}
                    </span>
                  </template>
                </el-table-column>
              </el-table>
            </ContentWrap>
          </el-col>
        </el-row>
      </el-col>

      <el-col :xs="24" :sm="24" :md="10" :lg="8" :xl="8">
        <ContentWrap>
          <h4>告警概览</h4>
          <el-table v-loading="loading" :data="warnList" height="630" :stripe="true" :show-overflow-tooltip="true" style="overflow-x: auto;">
            <el-table-column label="序号" type="index" fixed="left" align="center" key="id" prop="id" width="60"/>
            <el-table-column label="农舍" fixed="left" align="center" prop="farmHouseName" />
            <el-table-column label="告警类型" align="center" prop="faultMsg" />
            <el-table-column label="告警内容" align="center" prop="detail" />
            <el-table-column label="告警时间" align="center" prop="startTime" :formatter="dateFormatter"/>
            <el-table-column label="持续时长" align="center" fixed="right">
              <template #default>
                <span style="color: red;">未处理</span> <!-- 直接返回 "未处理" -->
              </template>
            </el-table-column>
          </el-table>
        </ContentWrap>
      </el-col>
    </el-row>
  </ContentWrap>
</template>

<script setup lang="ts">
  import { formatDate,dateFormatter } from '@/utils/formatTime'

  import { ref,watch } from 'vue';
  import { useI18n } from 'vue-i18n';
  import { FarmTourApi,FarmTourVO } from '@/api/farmTour/index';
  import { tr } from 'node_modules/element-plus/es/locale';
  import { get } from 'http';
  import { Loading } from 'node_modules/element-plus/es/components/loading/src/service';
  import { log } from 'console';
  import axios from 'axios';
  defineOptions({ name: 'Overview' })

  const { t } = useI18n();
  const farmTourValue = ref<any>('')
  const farmTourList = ref<FarmTourVO[]>([])
  const loading = ref(true) // 列表的加载中
  const monitorListLoading = ref(true)
  const FXJloading = ref(true)
  const FXGloading = ref(true)
  const farmId = ref<number>(0)//默认农场id

  const status = ref<number>(96.8)//设备状态
  const number = ref<number>(1)//设备总数
  const deviceStatus = ref<number>(0)//运行状态占比
  const alarm = ref<number>(0)//实时告警数量

  const eggNUmber = ref<number>(0)//今日产蛋

  const weatherList = ref([])//天气

  // 农舍概览
  interface houseListVo{
    houseName: string;
    day: number;
    column: number;
    outdoorTemperature: number;
    innerTemperature: number;
    humidity:number;
    pressure:number;
    speed:number;
    dead:number;
    water:number;
    consume:number;
    power:number;
    status:any

  }
  const houseList = ref<Array<houseListVo>>([])
  const getStatusText = (status) => {
    switch (status) {
      case 1: return '在线';
      case 0: return '离线';
      case 2: return '告警';
      default: return '未知状态';
    }
  };
  // 根据状态返回颜色
  const getStatusColor = (status) => {
    switch (status) {
      case 1: return 'green'; // 在线
      case 0: return 'gray'; // 离线
      case 2: return 'red'; // 告警
      default: return 'black'; // 默认颜色
    }
  };

  // 蛋库概览
  const activeName = ref('first')

  // 装托机
  interface ZTJListVO {
    deviceName: String;
    number: number;
    devecetime: any;
    store:number;
  }
  const ZTJList = ref<Array<ZTJListVO>>([])

  // 告警概览
  interface WarnVO {
    deviceName: String;
    number: number;
    devecetime: any;
    store:number;
  }
  const warnList = ref<Array<WarnVO>>([])
  //分选机
  interface sortDevice {
    devicecode: String;
    num: string;
    status: number;
    sqltime: any;
    store: string;
    devweighticeType: number;
  }
  const getSortDeviceList = ref<sortDevice[]>([]);//分选设备
  const getFJGDeviceList = ref([]);//发酵罐
  const total = ref(0) // 列表的总页数
  const queryParams = reactive({
    farmId:undefined as undefined | number,
  })
  const formatWorkTime = (timestamp) => {
    return timestamp ? (timestamp /1000 / 3600).toFixed(2) : '-'; // 将时间戳转换为小时
  }

  // 获取下拉农场列表
  const getList = async () => {
    const res  = await FarmTourApi.getFarmTour()
    if (res) {
      farmTourList.value = res

      // 设置默认选择第一个农场
      if (farmTourList.value.length > 0) {
        farmTourValue.value = farmTourList.value[0].id;
        farmId.value = farmTourValue.value;
        console.log(farmId.value,'farmId.value');
      }
    }
  }
  //天气信息
  const fetchWeatherData = async () => {
    const params = {
      farmId:farmId.value
    }
    try {
      const res = await FarmTourApi.getWeather(params)
      console.log(res.data.observe,'res天气预报')
      weatherList.value = res.data.observe
    } catch (error) {
      ElMessage.error('获取天气数据失败');
      console.error(error);
    } finally {
    }
  };
  // 今日产蛋
  const getEgg =async (farmHouseId) => {
    loading.value = true
    queryParams.farmId = farmId.value;
    try {
      const res = await FarmTourApi.getEggNumApi(queryParams);
      if (res&& res.length > 0) {
          eggNUmber.value = res[0].num;  // 提取产蛋数量
          console.log(eggNUmber.value, '今日产蛋数量');
      } else {
          eggNUmber.value = 0; // 如果没有数据或返回异常，设置为0
      }
    } catch (error) {
        console.error('获取今日产蛋数据时出错:', error);
        eggNUmber.value = 0;  // 设置为0以防止显示错误
    }finally{
      loading.value = false
    }
  }

  // 设别运行状态
  const getStatus =async () => {
    queryParams.farmId = farmId.value;
    const res = await FarmTourApi.getWarn(queryParams);
    if(res){
      console.log(res,'resgetStatus')
      number.value = res.total;
      deviceStatus.value = res.normal / res.total * 100;
      alarm.value = res.alarm;
    }
  }

  // 农舍概览
const getMonitorList = async () => {
  try {
    monitorListLoading.value = true; // 开始加载
    queryParams.farmId = farmId.value;
    const res = await FarmTourApi.getMonitorPage(queryParams);
    if (res) {
      houseList.value = res.list;
      total.value = res.list.length;
    }
  } catch (error) {
    console.error('获取农舍数据时出错:', error);
  } finally {
    monitorListLoading.value = false; // 结束加载
  }
};

  // 分选设备
  const getSortDeviceData = async () => {
    FXJloading.value = true
    // 1.获取农场id
    const farmSortId = farmId.value;
    // 构造请求参数
    const params = {
      farmId: farmSortId
    };
    const res = await FarmTourApi.getSortDeviceApi(params);
    if (res) {
      try{
        console.log(res,'resgetSortDevice')
        getSortDeviceList.value = res;
      }catch (error) {
        console.log(error,'error')
      }finally{
        FXJloading.value = false
      }
    }
  }
  // 装托机
  const getZTJDeviceData = async () => {
    FXJloading.value = true
    const farmSortId = farmId.value;
    const params = { farmId: farmSortId };
    const res = await FarmTourApi.getZTJDeviceApi(params);
    if (res) {
      try{
        ZTJList.value = res;
      }catch (error) {
        console.log(error,'error')
      }finally{
        FXJloading.value = false
      }
    }
  }
  
  // 发酵罐
  const getFJGDeviceData = async () => {
    FXGloading.value = true
    // 1.获取农场id
    const farmFJGId = farmId.value;
    // 构造请求参数
    const params = {
      farmId: farmFJGId
    };
    const res = await FarmTourApi.getFJGDeviceApi(params);
    console.log(res,'resgetFJGDevice')
    if (res) {
      try{
        getFJGDeviceList.value = res
      }catch (error) {
        console.log(error,'error')
      }finally{
        FXGloading.value = false
      }

    }
  }
  //实时告警
  const getNowWarn = async () => {
    const farmWarn = farmId.value;
    // 构造请求参数
    const params = {
      farmId: farmWarn
    };
    const res = await FarmTourApi.getNowWarnApi(params)
    try{
      loading.value = true;
      if (res) {
        console.log(res,'res告警概览')
        warnList.value = res;
      }
    }catch(error){
      console.log(error,'error')
    }finally{
      loading.value = false;
    }

  }

  // 定义异步处理函数
const fetchData = async () => {
  try {
    farmId.value = farmTourValue.value; // 更新 farmId
    fetchWeatherData()//天气
    getMonitorList();
    getSortDeviceData();
    getZTJDeviceData();//装托机
    getFJGDeviceData();
    getEgg();
    getStatus();
    getNowWarn();

  } catch (error) {
    console.error('获取数据时出错:', error);
  }
};

// 监听 farmTourValue 的变化
watch(farmTourValue, (newValue) => {
  fetchData(); // 调用异步处理函数
});

  onMounted( () => {
    getList()
  })
</script>

<style scoped lang="scss">
  h2{
    margin: 10px;
  }
  .container-card {
    display: flex;
    justify-content: space-between;
    .card-list {
      border-radius: 8px;
      flex: 1 1 calc(25% - 10px);
      margin: 10px;
      color: #ffffff;
      // 天气
      .list-item-weather{
        .list-item-top{
          display: flex;
          flex-direction: row;
          padding: 8px;
          justify-content: space-between;
          .top-weather{
            display: flex;
            justify-content: space-around;
            .top-temp{
              margin-right: 5px;
              font-size: 22PX;
              font-weight: bold;
            }
            .top-condition{
              margin-left: 5px;
            }
          }
          img{
            width: 2.5rem;
            height: 2.5rem;
          }
        }
        .middle-weather{
          display: flex;
          justify-content: space-between;
          flex-wrap: wrap;
          .middle-humi{
            flex: 1 1 calc(50% - 8px);
            display: flex;
            align-items: center;
            margin-bottom: 10px;
            img{
              width: 1.5rem;
              height: 1.5rem;
            }
            text{
              margin-left: 6px;
              font-size: 20px;
              font-weight: bold;
            }
          }
        }
      }

      // 告警、设备运行、产量
      .list-item{
        color: #ffffff;
        font-size: 20px;
        padding: 0px 10px;
        display: flex;
        justify-content:space-between;
        .item-device-left{
          .device-box-status{
            display: block;
            .status{
              margin: 10px 0px;
            }
            .status-persent{
              font-size: 26px;
              font-weight: bold;
            }
          }
        }
        .item-device-right{
          padding: 10px 0px;

        }
      }
    }
  }

  //农舍监控
  .house-monitor{
    .el-col {
      margin-top: 8px;
      margin-bottom: 8px;
    }

    img{
      width: 100%;
      height: 100%;
      fill: cover;
    }
    :deep(.el-card__footer) {
      background-image: url("@/assets/imgs/iot/monitorBackground.svg");
      background-size: cover; 
      background-repeat: no-repeat;
      object-fit: cover;
      color: #ffffff;
    }
    .monitor-list-title{
      font-size: 20px;
      font-weight: bold;
    }
    .monitor-list-content{
      display: flex;
      margin: 10px 0px;
      justify-content: space-between;
      align-items: center;
    }
  }

  // 分选设备
  .sort{
    .card-list{
      margin: 10px 0px;
      .sort-card{
        display: flex;
        flex-wrap: wrap;
        justify-content: center;
        align-items: center;
        .caed-left{
          flex: 1;
          margin-right: 8px;
          img{
            object-fit: cover;
          }
        }
        .caed-right{
          flex: 2;
          margin-left: 8px;
            :deep(.el-descriptions__title) {
              font-size: 22px ; /* 确保样式生效 */
            }
            // 对于描述组件的样式改变使用deep
            :deep(.label-class-name) {
              color: #666666;
              font-size: 14px;
              font-weight: bold;
              font-style: normal;
            }
            :deep(.class-name) {
              color: #666666;
              font-size: 14px;
              font-weight: 400;
              font-style: normal;
            }
        }
    }
    }
    
  }



</style>
